/*
 * 描述
 * Created by: litangyu
 * 包含类名列表
 * 版本信息，版本号 v1.0
 * 创建日期 16/8/31
 * 版权声明
*/
package com.foton.logistic.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.foton.logistic.R;
import com.foton.logistic.adapter.UploadImageAdapter;
import com.foton.logistic.base.BaseActivity;
import com.foton.logistic.base.BaseApplication;
import com.foton.logistic.listener.IOnDeleteListener;
import com.foton.logistic.listener.IOnDialogListener;
import com.foton.logistic.listener.IOnResultListener;
import com.foton.logistic.task.DispatchTask;
import com.foton.logistic.task.ShowDialogTask;
import com.foton.logistic.task.TaskConstant;
import com.foton.logistic.util.BaseConstant;
import com.foton.logistic.util.BroadcastUtil;
import com.foton.logistic.util.OptionUtil;
import com.foton.logistic.util.SharedUtil;
import com.foton.logistic.util.image.ImageChooseUtil;
import com.foton.logistic.util.net.HttpUtil;
import com.foton.logistic.util.tool.DataCleanManager;
import com.foton.logistic.util.tool.LogUtil;
import com.foton.logistic.util.tool.StringUtil;
import com.foton.logistic.view.MyGridView;
import com.foton.logistic.view.chooseimages.ImagesPreviewUtil;
import com.foton.logistic.view.dialog.DialogUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.InjectView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

/**
 * 描述
 * 异常上报
 * Created by: litangyu<br/>
 * Created on: 16/8/31 下午4:07
 */
@RuntimePermissions
public class UploadAbnormalActivity extends BaseActivity {

    @InjectView(R.id.ft_ui_upload_abnormal_images)
    public MyGridView uploadImages;

    @InjectView(R.id.ft_ui_upload_abnormal_other_reason)
    public LinearLayout otherReason;

    @InjectView(R.id.ft_ui_upload_abnormal_reason)
    public TextView reasonView;
    @InjectView(R.id.ft_ui_upload_abnormal_message)
    public EditText reasonMessage;

    private UploadImageAdapter adapter;

    private String orderId;
    private String reason;
    //当异常原因为其他时为true
    private boolean otherReasonFlag=true;

    private int statusBarHeight;

    private int addImagePosition = -1;
    private ImageChooseUtil imageChooseUtil;
    private ArrayList<String> mSelPhotos;
    //获取地址
    private String address = "";
    private GeoCoder mSearch;
    public DialogUtil dialogUtil;
    public PopupWindow loadPopupWindow;//加载框
    ArrayList<String>list=new ArrayList<>();
    ArrayList<String>list1=new ArrayList<>();
    ArrayList<String>list2=new ArrayList<>();
    private String station;
    private int status;
    private String[] abnormalArray1;
    private PopupWindow myPopuwindiw;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        setTaskTag(getClass().getSimpleName());
        setContentView(R.layout.ft_ui_upload_abnormal);
    }

    @Override
    public void init() {
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(listener);
        dialogUtil = new DialogUtil(this);

        setBackLayoutVisibility(View.VISIBLE);
        setTitleText(getString(R.string.upload_abnormal));
        setTitleTextVisibility(View.VISIBLE);

        statusBarHeight = OptionUtil.getStatusBarHeight(this);
        imageChooseUtil = new ImageChooseUtil(this);

        mSelPhotos = new ArrayList<>();

        adapter = new UploadImageAdapter(this, mSelPhotos, BaseConstant.MAX_PHOTO, false);
        uploadImages.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            private ImagesPreviewUtil imagesPreviewUtil;

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == mSelPhotos.size()) {
                    addImagePosition = position;
                    //imageChooseUtil.doTakePhotos();
                    UploadAbnormalActivityPermissionsDispatcher.checkPhotoWithCheck(UploadAbnormalActivity.this);
                } else {
                    if (null == imagesPreviewUtil) {
                        imagesPreviewUtil = new ImagesPreviewUtil
                                (UploadAbnormalActivity.this, mSelPhotos, titleText);
                        imagesPreviewUtil.setShowDelete(true);
                        imagesPreviewUtil.setStatusBarHeight(statusBarHeight);
                        myPopuwindiw =imagesPreviewUtil.showImagesPreview(position);
                        imagesPreviewUtil.setiOnDeleteListener(new IOnDeleteListener() {
                            @Override
                            public void onDelete(int position) {
                                adapter.notifyDataSetChanged();
                            }
                        });
                    } else {
                        myPopuwindiw =imagesPreviewUtil.showImagesPreview(position);
                    }
                }
            }
        });
        uploadImages.setAdapter(adapter);

        getOrderId();

        address = SharedUtil.getAddress(this);
        LogUtil.e("address= " + address);
        if (StringUtil.isEmpty(address)){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    loadPopupWindow = dialogUtil.showLoadDialog(titleText, "获取当前地址");
                    LatLng ll = new LatLng(Double.parseDouble(SharedUtil.getLat(BaseApplication.self())),Double.parseDouble(SharedUtil.getLng(BaseApplication.self())));
                    ReverseGeoCodeOption options = new ReverseGeoCodeOption().location(ll);
                    // 发起反地理编码请求
                    mSearch.reverseGeoCode(options);
                }
            },500);

        }else {
            OptionUtil.addToast(BaseApplication.self(),"获取当前地址成功");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loadPopupWindow!=null) {
            loadPopupWindow.dismiss();
        }
        if (myPopuwindiw!=null) {
            myPopuwindiw.dismiss();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        getOrderId();
    }

    /**
     * 获取订单编号
     */
    private void getOrderId() {
        if (null != getBundle()) {
            orderId = getBundle().getString(BaseConstant.INTENT_ID, "");
            status =getBundle().getInt(BaseConstant.INTENT_ST,0);
        }
    }

    @OnClick({R.id.ft_ui_upload_abnormal_select_reason, R.id.ft_ui_upload_abnormal_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ft_ui_upload_abnormal_select_reason:
                AlertDialog.Builder builder = new AlertDialog.Builder(UploadAbnormalActivity.this);
                //builder.setIcon(R.drawable.ic_launcher);
                builder.setTitle("异常信息");
                //final String[] hobbies = {"篮球", "足球", "网球", "斯诺克","ss球", "p球", "a球", "q克"};
                if (status==1){
                     abnormalArray1 = getResources().getStringArray(R.array
                            .abnormal_string_list1);
                }else if (status==10||status==2){
                    abnormalArray1 = getResources().getStringArray(R.array
                            .abnormal_string_list2);
                }else if (status==20||status==21||status==3){
                    abnormalArray1 = getResources().getStringArray(R.array
                            .abnormal_string_list3);
                }else if (status==40||status==30||status==4||status==41){
                    abnormalArray1 = getResources().getStringArray(R.array
                            .abnormal_string_list4);
                }else {
                    abnormalArray1 = getResources().getStringArray(R.array
                            .abnormal_string_list4);
                }

                //    设置一个单项选择下拉框
              /*  *
                 * 第一个参数指定我们要显示的一组下拉多选框的数据集合
                 * 第二个参数代表哪几个选项被选择，如果是null，则表示一个都不选择，如果希望指定哪一个多选选项框被选择，
                 * 需要传递一个boolean[]数组进去，其长度要和第一个参数的长度相同，例如 {true, false, false, true};
                 * 第三个参数给每一个多选项绑定一个监听器
*/
                builder.setMultiChoiceItems(abnormalArray1, null, new DialogInterface.OnMultiChoiceClickListener() {
                    //StringBuffer sb = new StringBuffer(100);

                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        if (isChecked) {
                            list1.clear();
                            list.add(abnormalArray1[which]);
                            Log.e("+++++++++++", "onClick: "+list);
                            //sb.append(hobbies[which] + ", ");
                            Log.e("___________", "onClick: "+list1);
                        }else {
                            list1.add(abnormalArray1[which]);
                            list.removeAll(list1);
                            //list.remove(which);
                            Log.e("+++++++++++", "onClick: "+list);
                            Log.e("___________", "onClick: "+list1);
                        }
                        list2.clear();
                        for (int i = 0; i < list.size(); i++) {
                            list2.add(list.get(i));
                        }

                        //s =new String(sb);
                        // Toast.makeText(MainActivity.this, "爱好为：" + sb.toString(), Toast.LENGTH_SHORT).show();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    StringBuffer sb = new StringBuffer(100);
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        int size=list.size();
                        String[] array = (String[])list.toArray(new String[size]);

                        for (int i = 0; i <array.length ; i++) {
                            sb.append(array[i] + " ");
                        }
                        station =new String(sb);
                        reasonView.setText(station);
                        list.clear();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        list.clear();
                    }
                });
                builder.show();

               /* DialogUtil dialog = new DialogUtil(this);
                final ArrayList<String> reasons = new ArrayList<>();
                String[] abnormalArray = getResources().getStringArray(R.array.abnormal_string_list);
                Collections.addAll(reasons, abnormalArray);
                dialog.setDismissKeyback(true);
                dialog.setDismissOutside(true);
                dialog.showListDialog(containLayout, reasons);
                dialog.setiOnItemClickListener(new IOnItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        if (reasons.size() - 1 == position) {
                            otherReasonFlag = true;
                            otherReason.setVisibility(View.VISIBLE);
                        } else {
                            otherReasonFlag = false;
                            otherReason.setVisibility(View.GONE);
                            reason = reasons.get(position);
                        }
                        reasonView.setText(reasons.get(position));
                    }
                });*/
                break;
            case R.id.ft_ui_upload_abnormal_submit:
                uploadAbnormal();
                break;
        }
    }

    private void uploadAbnormal() {
        if (otherReasonFlag) {
            if (StringUtil.isEmpty(reasonMessage.getText().toString())) {
                OptionUtil.addToast(this, getString(R.string.other_message_hint));
                return;
            } else {
                reason = reasonMessage.getText().toString().trim()+","+station;
            }
        } else {
            if (StringUtil.isEmpty(reason)) {
                OptionUtil.addToast(this, getString(R.string.select_reason));
                return;
            }
        }
        request();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            if (resultCode == RESULT_OK) {
                switch (requestCode) {
                    case ImageChooseUtil.PHOTO_WITH_CAMERA: // 照相机程序返回的
                        String imagePath = imageChooseUtil.getTakePhotoScaleUrl(address);
//                        bm = BitmapFactory.decodeFile(imagePath);
//                        //加水印
//                        ImageChooseUtil.saveTimeFlag(bm,imagePath);
                        DataCleanManager.DeleteFile(new File(imageChooseUtil.getTakePhotosUrl()));
                        if (!StringUtil.isEmpty(imagePath) && addImagePosition != -1) {
                            mSelPhotos.add(imagePath);
                            adapter.notifyDataSetChanged();
                        } else {
                            OptionUtil.addToast(UploadAbnormalActivity.this, getString(R.string
                                    .tip8));
                        }
                        break;
                }
            }
            super.onActivityResult(requestCode, resultCode, data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void request() {
        String uploadImagePath = null;
        if (mSelPhotos.size()<2) {
            OptionUtil.addToast(this, getString(R.string.limit_photo));
            return;
        } else {
            for (String imagePath : mSelPhotos) {
                if (StringUtil.isEmpty(uploadImagePath)) {
                    uploadImagePath = imagePath;
                } else {
                    uploadImagePath = uploadImagePath + "," + imagePath;
                }
            }
        }
        List<File> fileList = OptionUtil.getImageList(uploadImagePath);
        if (station.contains("事故")){
            Map<String, Object> argMap = HttpUtil.getEncryMap(this);
            argMap.put("orderId", "" + orderId);
            argMap.put("reason", "" + reason);
            argMap.put("type", "9");
            argMap.put("lat", SharedUtil.getLat(this));
            argMap.put("lon", SharedUtil.getLng(this));
            argMap.put("address", SharedUtil.getAddress(this));
            ShowDialogTask task = new ShowDialogTask(this, taskTag, titleText, getString(R.string
                    .task3), true,
                    BaseConstant.UPLOAD_ABNORMAL_ACCIDENT, argMap, fileList, TaskConstant.UPLOADS);
            task.setiOnResultListener(new IOnResultListener() {
                @Override
                public void onOK(DispatchTask task) {
                    OptionUtil.addToast(UploadAbnormalActivity.this, getString(R.string
                            .upload_success));
                    BroadcastUtil.sendOrderRefreshBroadcast(UploadAbnormalActivity.this);
                    finishSelf();
                }

                @Override
                public void onError(DispatchTask task) {

                }

                @Override
                public void onDone(DispatchTask task) {

                }
            });
            task.execute();
        }else {
            Map<String, Object> argMap = HttpUtil.getEncryMap(this);
            argMap.put("orderId", "" + orderId);
            argMap.put("reason", "" + reason);
            argMap.put("type", "3");
            argMap.put("lat", SharedUtil.getLat(this));
            argMap.put("lon", SharedUtil.getLng(this));
            argMap.put("address", SharedUtil.getAddress(this));
            ShowDialogTask task = new ShowDialogTask(this, taskTag, titleText, getString(R.string
                    .task3), true,
                    BaseConstant.UPLOAD_ABNORMAL, argMap, fileList, TaskConstant.UPLOADS);
            task.setiOnResultListener(new IOnResultListener() {
                @Override
                public void onOK(DispatchTask task) {
                    OptionUtil.addToast(UploadAbnormalActivity.this, getString(R.string
                            .upload_success));
                    BroadcastUtil.sendOrderRefreshBroadcast(UploadAbnormalActivity.this);
                    finishSelf();
                }

                @Override
                public void onError(DispatchTask task) {

                }

                @Override
                public void onDone(DispatchTask task) {

                }
            });
            task.execute();
        }
    }

    OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
        public void onGetGeoCodeResult(GeoCodeResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有检索到结果
            }
            //获取地理编码结果
        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
            LogUtil.e("result.error= "+result.error);
            if (loadPopupWindow!=null)
                loadPopupWindow.dismiss();
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有找到检索结果
                dialogUtil.setOptionCount(1);
                dialogUtil.showTipDialog(titleText,"获取当前地址失败，请退出界面后重试");
                dialogUtil.setiOnDialogListener(new IOnDialogListener() {
                    @Override
                    public void onConfirm() {
                        finishSelf();
                    }

                    @Override
                    public void onCancel() {

                    }

                    @Override
                    public void onOther() {

                    }
                });
            }else {
                //获取反向地理编码结果
                address = result.getAddress();
                OptionUtil.addToast(BaseApplication.self(),"获取当前地址成功");
            }

        }
    };

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void checkPhoto() {
        imageChooseUtil.doTakePhotos(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        UploadAbnormalActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
}
